package com.finance.cooperate.data.web.controller;

import com.finance.cooperate.common.constant.CodeMsg;
import com.finance.cooperate.common.pojo.RestResult;
import com.finance.cooperate.common.utils.StringUtil;
import com.finance.cooperate.dao.local.scope.CooperateRequestScope;
import com.finance.cooperate.data.builder.FeatureProcess;
import com.finance.cooperate.data.builder.ReaderBuilder;
import com.finance.cooperate.data.service.ApplyService;
import com.finance.cooperate.data.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClassName FeatureController
 * @Description TODO
 * @Author shen
 * @Date 2023/8/10 21:51
 * @Modify ...
 */
@RestController
@RequestMapping("/api/v1.0/feature")
@Slf4j
public class FeatureController {

    @Autowired
    private CooperateRequestScope requestScope;

    @Autowired
    private ApplyService applyService;

    @Autowired
    private UserService userService;


    @PostMapping("/{loanNum:\\d+}/{applyId}")
    public RestResult feature(@PathVariable Long loanNum, @PathVariable String applyId) {

        requestScope.setLoanNum(loanNum);

        log.info("applyId:" + applyId);

        // 根据 applyId 查询出用户 id
        String uid = applyService.getUidByApplyId(applyId);

        if (StringUtil.isEmptyOrNvl(uid)) {
            // 说明有问题
            return RestResult.build(CodeMsg.USER_ID_PARAMS_NULL);
        }

        requestScope.setUserId(uid);
        requestScope.setApplyId(applyId);

        // 缓存设备id
        try {

            String deviceId = userService.getDeviceId(uid);

            requestScope.setDeviceId(deviceId);

        } catch (Exception e) {
            e.printStackTrace();
        }


        return new FeatureProcess()
                .run(uid, new ReaderBuilder());

    }


}
